package com.zsk.tool.http;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.*;

import java.io.IOException;
import java.util.ArrayList;

/**
 * okhttp客户端
 * <p>1. 忽略https证书验证
 * <p>2. 最大3次请求容错机制
 * <p>3. 连接池
 *
 * @author: keke
 * @date: 2021/11/19
 */
public class HttpFactory {

    private static final int totalRetryTimes = 3;

    /**
     * @param ignoreSsl 忽略ssl
     * @return
     */
    public static OkHttpClient createOkHttpClient(boolean ignoreSsl) {
        if (!ignoreSsl) {
            return new OkHttpClient();
        }

        OkHttpClient.Builder builder = createOKHttpBuilder();
        SSLSocketFactory sslFactory = SslSocketClient.getSslSocketFactory();
        X509TrustManager x509TrustManager = SslSocketClient.getTrustManager()[0];
        builder.sslSocketFactory(sslFactory, x509TrustManager)
                .hostnameVerifier(SslSocketClient.getHostnameVerifier())
                .connectionPool(new ConnectionPool())
                // java.io.IOException unexpected end of stream on xxx
                // 容错拦截器，当服务断开长连接时最大尝试3次请求
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        Response response = null;
                        try {
                            response = chain.proceed(request);
                            return response;
                        } catch (IOException e) {

                        }
                        int tryTimes = 0;
                        while (tryTimes++ < totalRetryTimes) {
                            try {
                                response = chain.proceed(request);
                                return response;
                            } catch (IOException e) {
                                if (tryTimes == totalRetryTimes) {
                                    throw e;
                                }
                            }
                        }
                        return null;
                    }
                });
        return builder.build();
    }

    public static OkHttpClient.Builder createOKHttpBuilder() {
        return new OkHttpClient.Builder();
    }

}
